import * as actionType from '../actions/actionType';

const initState = {
  list: JSON.parse(window.localStorage.getItem('wgd-cart')) || []
}

const syncCartStorage = (cartlist)=> {
  window.localStorage.setItem('wgd-cart', JSON.stringify(cartlist));
}

export default (state =  initState, action)=> {
  switch(action.type) {
    case actionType.CART_REDUCE:
      const newList = state.list.reduce((result, item)=> {
        if(item.id === action.id) {
          item.count =item.count - 1;
        }
        if(item.count > 0){
          result.push(item);
        }
        return result;
      }, [])
      syncCartStorage(newList);
      return Object.assign({}, state, {
        list: newList
      });
    case actionType.CART_ADD:
      const newAddList = state.list.map(item => {
        if(item.id === action.id) {
          item.count =item.count + 1;
        }
        return item;
      })
      syncCartStorage(newAddList);
      return Object.assign({}, state, {
        list: newAddList
      });
    case actionType.ADD_TO_CART:
      const { cartItem } = action;
      const isInCartList = state.list.some(item => item.id === action.cartItem.id);
      if(isInCartList) {
        const newAddList = state.list.map(item => {
          if(item.id === cartItem.id) {
            item.count =item.count + 1;
          }
          return item;
        })
        syncCartStorage(newAddList);
        return Object.assign({}, state, {
          list: newAddList
        });
      } else {
        cartItem.count = 1;
        const newList = state.list.concat(cartItem);
        syncCartStorage(newList);
        return Object.assign({}, state, {
          list: newList
        })
      }
    default:
      return state;
  }
}